import { move } from "./move.js";
function Banner({ left, right, data, imgbox, box, index = 0 }) {
  this.index = index;
  this.box = box;
  this.imgbox = imgbox;
  this.left = left;
  this.right = right;
  this.data = data;
  this.init()
  this.addEvent();
  this.moveIndex();
}

// 添加元素
Banner.prototype.init = function () {
  let str = '';
  this.data.forEach(key => {
    str += `<img src="${key.src}" alt="${key.name}">`
  });
  this.imgbox.innerHTML = str;
  this.Width = this.imgbox.children[0].offsetWidth
  for(let i = 0;i<this.imgbox.children.length;i++){
    this.imgbox.children[i].style.width = this.Width+'px'
  }
  this.imgbox.style.width = this.data.length * this.Width + 'px';
  this.imgbox.style.left = -this.Width * this.index + 'px';
}


// 添加事件
Banner.prototype.addEvent = function () {
  const that = this;
  this.left.onclick = function () {
    that.computedIndex('left')
  };
  this.right.onclick = function () {
    that.computedIndex('rigth')
  };
}

// 自动移动轮播图
Banner.prototype.moveIndex = function () {
  const that = this;
  if (this.t) return;
  this.t = setInterval(() => {
    
    this.index === this.data.length - 1 ? this.index = 0 : this.index++;
    move(that.imgbox, {
      left: -that.Width * that.index
    })
  }, 2000)
}

// 切换轮播图索引
Banner.prototype.computedIndex = function (data) {
  if (data === 'left') {
    this.index === 0 ? this.index = this.data.length - 1 : this.index--
  } else {
    this.index === this.data.length - 1 ? this.index = 0 : this.index++
  }
  this.changeImg(this.index)
}

//改变图片
Banner.prototype.changeImg = function (index) {
  clearInterval(this.t)
  this.t = null
  move(this.imgbox, {
    left: -this.Width * index
  })
  this.moveIndex()
}
export{ Banner }